package org.quickjsf.core.datamodel;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.quickjsf.common.util.DomainUtil;
import org.quickjsf.core.base.dao.PageModel;
import org.quickjsf.core.base.viewmodel.vo.FieldFilter;

public class DBLazyDataModel<T> extends LazyDataModel<T> implements Serializable{ 
	/**
	 * 
	 */
	private static final long serialVersionUID = -338716672020668249L;
	private transient IDataModel<T> modelSupport;
	private List<FieldFilter> fieldFilters;
	
	public DBLazyDataModel() {
		fieldFilters = new ArrayList<FieldFilter>(0);
	}
	
	public List<FieldFilter> getFieldFilters() {
		return fieldFilters;
	}

	@Override
	public void setRowIndex(int rowIndex) {
       if (getPageSize() == 0) {
            rowIndex = -1;
        }
        super.setRowIndex(rowIndex);
	}
	
	@Override
    public Object getRowKey(T object) {
		if (null == object) return null;
		Object value = null;
    	try {
    		value = DomainUtil.getFieldIdValue(object);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return value;
    }
    
	@Override
    public T getRowData(String rowKey) {
//    	Collection<T> datas = (Collection<T>) getWrappedData();
//    	if (datas == null) {
//    		Integer id = Integer.valueOf(rowKey);
//    		return this.service.getById(id);
//    	}
//    	for (T item : datas) {
//			try {
//				if (DomainUtil.getFieldIdValue(item).toString().equals(rowKey)) {
//					return item;
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//    	return null;
		return this.modelSupport.getModel(rowKey);
    }
	
//	@Override
//	public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
//		PageModel<T> pageModel = service.getTableList(first, pageSize, sortField, sortOrder==null?null:sortOrder.name(), getCriterions());
//		this.setRowCount(pageModel.getTotalCount());
//		List<T> datas = pageModel.getDatas();
//		if (datas.size() < pageSize) {
//			int fillEntityNum = pageSize - datas.size();
//			for (int i = 0; i < fillEntityNum; i++) {
//				datas.add(null);
//			}
//		}
//		return datas;
//	}
	@Override
	public List<T> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
		PageModel<T> pageModel = this.modelSupport
				.getPageModel(first, pageSize, sortField, sortOrder==null?null:sortOrder.name(), fieldFilters);
		this.setRowCount(pageModel.getTotalCount());
		List<T> datas = pageModel.getDatas();
		if (datas.size() < pageSize) {
			int fillEntityNum = pageSize - datas.size();
			for (int i = 0; i < fillEntityNum; i++) {
				datas.add(null);
			}
		}
		return datas;
	}

	public void setModelSupport(IDataModel<T> support) {
		this.modelSupport = support;
	}
}
